package com.jiahao.material.configs;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiahao.material.entity.Permission;
import com.jiahao.material.entity.Role;
import com.jiahao.material.entity.TokenEntity;
import com.jiahao.material.entity.User;
import com.jiahao.material.services.ITokenEntityService;
import com.jiahao.material.services.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private ITokenEntityService tokenEntityService;

    @Autowired
    private IUserService userService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        User user = (User) principalCollection.getPrimaryPrincipal();
        List<Role> roles = user.getRoles();

        //添加角色和权限
            Set<String> r= new HashSet<>();
        Set<String> p = new HashSet<>();
        for (Role role : roles) {
            r.add(role.getName());
            List<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                p.add(permission.getCode());
            }
        }
        simpleAuthorizationInfo.setRoles(r);
        simpleAuthorizationInfo.setStringPermissions(p);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getPrincipal();

        QueryWrapper<TokenEntity> tokenEntityQueryWrapper = new QueryWrapper<>();
        tokenEntityQueryWrapper.eq("token",token);
        TokenEntity one = tokenEntityService.getOne(tokenEntityQueryWrapper);

        if (one==null || one.getExpireTime().getTime()< System.currentTimeMillis()){
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }

        User byId = userService.getUserById(one.getUid());


        if (byId==null){
            throw new UnknownAccountException("用户不存在!");
        }

        if (byId.getStatus().equals("00")){
            throw new LockedAccountException("用户已被冻结!");
        }

        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(byId,token,this.getName());


        return info;
    }
}
